import {
  getTenementPage, // 分页查询
  editTenement, // 新增/修改
  editTenementStatus, // 修改status
  getTenementNumber, // 企业总数
  getTenementDatil, // 关联商详情
  delData
} from '@/api/tenement'

const getTenementState = () => {
  return {
    size: 14,
    current: 1,
    conditions: {},
    detailList: '',
    tenementNumber: ''
  }
}

const state = getTenementState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getTenementState())
  },
  // 更新state中的conditions
  UPDATE_CONDITIONS: (state, payload = {}) => {
    const { conditions } = state
    state.conditions = payload ? { ...conditions, ...payload } : {}
  },
  SET_LISTS: (state, { res, dataName }) => {
    const { retData } = res || {}
    const { records } = retData || {}
    state[dataName] = records || []
  }
}

const actions = {
  // 企业管理分页
  async getTenementPage({ state, dispatch }, payload = {}) {
    const { current: newCurrent, size: newSize, ...conditions } = payload
    const newConditions = { ...state.conditions, ...conditions }
    state.loading = true
    const res = await getTenementPage({
      current: newCurrent || state.current,
      size: newSize || state.size,
      ...newConditions
    })
    const { retData } = res || {}
    const { records, total, current, size } = retData || {}
    Object.assign(state, {
      loading: false,
      woList: records || [],
      total,
      current,
      size,
      conditions: newConditions
    })
  },
  // 新增/编辑企业
  async onEditTenement({ dispatch, commit }, payload = {}) {
    const { success } = await editTenement(payload)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      commit('UPDATE_CONDITIONS')
    }
  },
  // Status
  async editTenementStatus({ dispatch, commit }, payload = {}) {
    const { success } = await editTenementStatus(payload)
    if (success) {
      commit('UPDATE_CONDITIONS')
    }
  },
  // 企业数量情况统计
  async getTenementNumber({ state, commit }) {
    const { retData } = await getTenementNumber()
    const data = retData || {}
    Object.assign(state, {
      tenementNumber: { data }
    })
  },
  // 查询详情
  async getTenementDatil({ state }, payload = {}) {
    const { retData } = await getTenementDatil(payload)
    const { companyIds, dmpAuthUser, dmpTenant } = retData || {}
    const { provinceCode, cityCode, countyCode } = dmpTenant || {}
    const address = [provinceCode, cityCode]
    if (countyCode) {
      address.push(countyCode)
    }

    const userId = dmpAuthUser && dmpAuthUser.id
    Object.assign(state, {
      detailList:
        {
          userId,
          companyIds,
          ...dmpAuthUser,
          ...dmpTenant,
          address
        } || {}
    })
  },
  // 删除
  async delData({ dispatch, commit }, payload = {}) {
    console.log(payload, 'payload')
    const { success } = await delData(payload)
    if (success) {
      commit('UPDATE_CONDITIONS')
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
